<?php

namespace app\yj\controller;

use app\yj\model\MapConfigModel;
use app\yj\model\MapsModel;
use app\yj\model\UserModel;
use think\Controller;
use think\Request;

class MapsController extends BaseAdminController
{
    public $mapsurldata = '';

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //
        $maps = MapsModel::select();
        $view = MapConfigModel::find(1);

        $data = ['maps' => $maps, 'view' => $view];
        return $this->SuccessReturn('ok', $data);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
        $all = $request->post();

        $name = array_key_exists('name', $all) ? $all['name'] : '未定义地图';
        $mapid = array_key_exists('mapid', $all) ? $all['mapid'] : '';
        $moren = array_key_exists('moren', $all) ? $all['moren'] : 0;


        if ($mapid == '') return $this->ErrorReturn(403, '缺少地图id');

        //获取bounds范围
        $res = MapConfigModel::field('mapurl')->find(1);
        $mapurl = $res['mapurl'];


        //判断是否存在mapid
        $ismap = MapsModel::where('mapid', $mapid)->find();
        if ($ismap) {
            return $this->ErrorReturn(400, '存在相同的mapid 请直接修改');
        }
        $bounds = $this->getBounds($mapurl, $mapid);

        if ($bounds == '') return $this->ErrorReturn(400, '地图id不对 重新填写');


        $crs = 3;

        switch ($this->mapsurldata['srs']) {
            case 'webmercator':
                $crs = 2;
                break;
            case 'wgs84':
                $crs = 1;
                break;
        }
        //保存
        $newmaps = new MapsModel();
        $newmaps->name = $name;
        $newmaps->mapid = $mapid;
        $newmaps->bounds = $bounds;
        $newmaps->crs = $crs;
        if ($moren == 1) {
            $moren_map = MapsModel::where('moren', 1)->find();
            if ($moren_map) {
                $moren_map->moren = 0;
                $moren_map->save();
            }
        }
        $newmaps->moren = $moren;
        $newmaps->save();
        return $this->SuccessReturn('ok', $newmaps);

    }

    function geturl($url)
    {
        $headerArray = array("Content-type:application/json;", "Accept:application/json");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($output, true);
        return $output;
    }

    function getBounds($mapurl, $mapid)
    {
        $bounds = [];
        $url = $mapurl . '/tokens/v1?access_token=none';
        $token = $this->geturl($url);
        if (array_key_exists('token', $token)) {
            //拼装获取bounds的url
            $boundsurl = $mapurl . '/v2/' . $mapid . '.json?access_token=' . $token['token'];
            $boundsdata = $this->geturl($boundsurl);

            if ($boundsdata['message'] == "Not Found") return '';

            $this->mapsurldata = $boundsdata;
            array_push($bounds, [$boundsdata[bounds][0], $boundsdata[bounds][1]]);
            array_push($bounds, [$boundsdata[bounds][2], $boundsdata[bounds][3]]);
            return $bounds;
        } else {
            return $bounds;
        }
    }

    /**
     * 显示指定的资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param int $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param \think\Request $request
     * @param int $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //

        $all = $request->post();
        $id = array_key_exists('id', $all) ? $all['id'] : '';
        $name = array_key_exists('name', $all) ? $all['name'] : '';
        $mapid = array_key_exists('mapid', $all) ? $all['mapid'] : '';
        $moren = array_key_exists('moren', $all) ? $all['moren'] : '';

        if ($id == '') return $this->ErrorReturn(403, '缺少必要的参数');

        //获取对象
        $mapdata = MapsModel::find($id);
        if (!$mapdata) return $this->ErrorReturn(400, '不存在地图');

        if ($name != '') $mapdata->name = $name;
        if ($mapid != '' && $mapid !== $mapdata->mapid) {
            //是否存在相同的mapid
            $maps_mapid = MapsModel::where('mapid', $mapid)->find();
            if ($maps_mapid) return $this->ErrorReturn(400, '存在相同的mapid');
            $mapconfig = MapConfigModel::find(1);
            $bounds = $this->getBounds($mapconfig->mapurl, $mapid);
            if ($bounds == '') return $this->ErrorReturn(400, '地图id不对 重新填写');
            $mapdata->bounds = $bounds;
            $mapdata->mapid = $mapid;
            $crs = 3;

            switch ($this->mapsurldata['srs']) {
                case 'webmercator':
                    $crs = 2;
                    break;
                case 'wgs84':
                    $crs = 1;
                    break;
            }
            $mapdata->crs = $crs;
            if ($moren == 1) {
                $moren_map = MapsModel::where('moren', 1)->find();
                if ($moren_map) {
                    $moren_map->moren = 0;
                    $moren_map->save();
                }
            }
            //判断crs参数

        }
        if ($moren !== '') {
            if ($moren == 1) {
                $moren_map = MapsModel::where('moren', 1)->find();
                if ($moren_map) {
                    $moren_map->moren = 0;
                    $moren_map->save();
                }
            }
            $mapdata->moren = $moren;
        }
        $mapdata->save();
        return $this->SuccessReturn('ok', $mapdata);

    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function delete($id, Request $request)
    {
        //
        //
        $id = $request->post('id');
        if ($id == 0) return $this->ErrorReturn(400, '用户id无效');
        //查询是否存在此用户
        $map = MapsModel::find($id);
        if (!$map) return $this->ErrorReturn(404, '找不到此地图');
        //检查是否是最后一个
        $count = MapsModel::count();
        if ($count <= 1) {
            return $this->ErrorReturn(200, '地图图层至少有一个 请先添加图层 然后删除');
        }
        //如果删除了默认图层 必须新添加一个
        if ($map->moren == 1) {
            $firstmap = MapsModel::find();
            $firstmap->moren = 1;
            $firstmap->save();
        }

        $map->delete();
        return $this->SuccessReturn('删除成功');
    }
}
